package com.server.llh.llhserverwork.activity.server;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.BaseFragment;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.SerTransWapBean;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.TiemUtils;
import com.server.llh.llhserverwork.utils.ToastTool;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by ZTF on 2017-03-28.
 * 服务预约
 */

public class LlhMySubscribeFragment extends BaseFragment {
    private static final String TAG="LlhMySubscribe";
    private static final String FRAGMENT_INDEX = "fragment_index";
    private final int FIRST_FRAGMENT = 0;
    private final int SECOND_FRAGMENT = 1;
    private int mCurIndex = -1;
    @BindView(R.id.query_subscribe)
    ListView querySubscribe;
    @BindView(R.id.refrash_data)
    SwipeRefreshLayout refrashData;
    Unbinder unbinder;
    View rootView;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private String userIdStr, userNameStr, userPhoneStr, token;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        userIdStr = SharedPreferenceUtil.getUserInfo("customerId", getActivity().getApplicationContext());
        token = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getActivity().getApplicationContext());

        // TODO: inflate a fragment view
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            isPrepared = true;
//            lazyLoad();
        }
        refrashData = (SwipeRefreshLayout) rootView.findViewById(R.id.refrash_data);
        refrashData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onRefreshReq();
            }
        });
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        reqServerSub(userIdStr);
    }
    @Override
    public void onResume() {
        onRefreshReq();
        super.onResume();
    }
    private void onRefreshReq() {
        if (mHasLoadedOnce == false || isPrepared == false || mHasLoadedOnce) {
            mHasLoadedOnce = true;
            isPrepared = true;
            mHasLoadedOnce = false;
        }
        lazyLoad();
    }

    private List<SerTransWapBean> serTransWapBeanList = new ArrayList<>();
    private void reqServerSub(String customerId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("userId", customerId);
        lRequest.addParam("token", token);
        lRequest.addParam("searchType", "1");
        lRequest.setUri(ServerPort.QUERY_MY_SUBSCRIBE);
        lRequest.setUriType(UrlsTools.SERVER_KUC_INFO);
        lRequest.setIp(UrlsTools.SERVER_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                try {
                    if (refrashData!=null){
                        refrashData.setRefreshing(false);
                    }
                    closeProgress();
                    T.showAnimErrorToast(getActivity().getApplicationContext(), "请求超时！");
                } catch (Exception E) {
                }
            }
            @Override
            public void onNext(String responseBean, String code) {
                Log.d(TAG, "responseBeanqqq==" + responseBean.toString());
                try {
                    if (refrashData!=null){
                        refrashData.setRefreshing(false);
                    }
                    closeProgress();
                } catch (Exception E) {
                }
                if (responseBean != null && "200".equals(code)) {
                    serTransWapBeanList.clear();
                    mHasLoadedOnce = true;
                    serTransWapBeanList=new Gson().fromJson(responseBean,new TypeToken<List<SerTransWapBean>>(){}.getType());
                    SearchDataAdapter searchDataAdapter=new SearchDataAdapter(getActivity().getApplicationContext(),serTransWapBeanList);
                    querySubscribe.setAdapter(searchDataAdapter);
                    searchDataAdapter.notifyDataSetChanged();
                }else{
                    mHasLoadedOnce = true;
                    T.showAnimToast(getActivity().getApplicationContext(),"没有查到数据！");
                }

            }
        });

    }
    class SearchDataAdapter extends BaseAdapter {
        List<SerTransWapBean> listData;

        public List<SerTransWapBean> getListData() {
            return listData;
        }

        public void setListData(List<SerTransWapBean> listData) {
            this.listData = listData;
        }

        private Context context;

        public SearchDataAdapter(Context context, List<SerTransWapBean> listData) {
            this.context = context;
            this.listData = listData;
        }

        @Override
        public int getCount() {
            if (listData == null || listData.size() == 0) {
                return 0;
            }
            return listData.size();
        }

        @Override
        public Object getItem(int position) {
            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public String dateToString(Date date) {
            String str = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            sdf.format(date);
            str = sdf.format(date).toString();
            return str;
        }

        @Override
        public View getView(final int position, View itemView, ViewGroup parent) {
            ViewHolder holder = null;
            if (itemView == null) {
                itemView = LayoutInflater.from(context).inflate(
                        R.layout.search_server_item, parent, false);
                holder = new ViewHolder();
                holder.server_time = (TextView) itemView
                        .findViewById(R.id.server_time);
                holder.server_time_content = (TextView) itemView
                        .findViewById(R.id.server_time_content);
                holder.server_rule_content = (TextView) itemView
                        .findViewById(R.id.server_rule_content);
                holder.server_rule = (TextView) itemView
                        .findViewById(R.id.server_rule);
                holder.server_surplus_num = (TextView) itemView
                        .findViewById(R.id.server_surplus_num);
                holder.server_content_num = (TextView) itemView
                        .findViewById(R.id.server_content_num);
                holder.server_content = (TextView) itemView
                        .findViewById(R.id.server_content);
                holder.gift_packs = (TextView) itemView
                        .findViewById(R.id.gift_packs);
                holder.uploadView = (TextView) itemView
                        .findViewById(R.id.uploadView);
                holder.transStatus = (TextView) itemView
                        .findViewById(R.id.transStatus);
                holder.serverName = (TextView) itemView
                        .findViewById(R.id.serverName);
                holder.server_address = (TextView) itemView
                        .findViewById(R.id.server_address);
                holder.server_num = (TextView) itemView
                        .findViewById(R.id.server_num);
                holder.server_centel = (TextView) itemView
                        .findViewById(R.id.server_centel);
                holder.server_finish_time = (TextView) itemView
                        .findViewById(R.id.server_finish_time);
                itemView.setTag(holder);
            } else {
                holder = (ViewHolder) itemView.getTag();
            }
            final SerTransWapBean searchInfo = listData.get(position);
            holder.server_time.setText("预约详情:");
            holder.server_time_content.setText("" + searchInfo.getTaskRecord());
            String startTimeStr = TiemUtils.dateToString(searchInfo
                    .getSerStartTime());
            String endTimeStr = TiemUtils.dateToString(searchInfo
                    .getSerEndTime());
            holder.server_rule_content.setText("开始时间:"+startTimeStr.substring(5,
                    startTimeStr.length() - 3)
                    +"\n"+ "结束时间:"
                    + endTimeStr.substring(5, endTimeStr.length() - 3));

            holder.server_rule.setText("服务时间:");
            String addTimeStr = TiemUtils.dateToString(searchInfo.getAddTime());

            holder.server_surplus_num.setText(""
                    + addTimeStr.substring(5, addTimeStr.length() - 3));
            holder.server_content_num.setText("");
            holder.server_content.setText("" + searchInfo.getServiceName());
            holder.gift_packs.setText("预约人:" + searchInfo.getCustomerName());
            String waiterName = searchInfo.getWaitersName();
            if (TextUtils.isEmpty(waiterName)) {
                holder.serverName.setText("");
            } else {
                holder.serverName.setText("" + searchInfo.getWaitersName());
            }			String transStatus = searchInfo.getTransStatus();
            if ("1".equals(transStatus)) {
                holder.transStatus.setText("状态:系统自动派");
                holder.server_centel.setText("取消");
                holder.server_address.setText("指派中");
                holder.server_centel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        long serTransId = searchInfo.getSerTransId();

                    }
                });
                holder.server_num.setVisibility(View.INVISIBLE);
            } else if ("2".equals(transStatus)) {
                holder.transStatus.setText("状态:客户指定");
                holder.server_centel.setText("乐老汇派");
                holder.server_address.setText("服务员已接");
                holder.server_num.setText("重派");
                holder.server_centel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        long serTransId = searchInfo.getSerTransId();

                    }
                });
                holder.server_num.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                    }
                });
            } else if ("3".equals(transStatus)) {
                holder.transStatus.setText("状态:服务员已拒");
                holder.server_centel.setText("乐老汇派");
                holder.server_address.setText("繁忙");
                holder.server_num.setText("重派");
                holder.server_centel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        ToastTool.showText(getActivity().getApplicationContext(), "乐老汇派送"
                                + position);
                        long serTransId = searchInfo.getSerTransId();

                    }
                });
                holder.server_num.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                    }
                });
            } else if ("4".equals(transStatus) || "5".equals(transStatus)) {
                holder.transStatus.setText("状态:服务员已接");
                holder.server_centel.setText("撤单");
                holder.server_address.setText("已确认");
                holder.server_finish_time.setText("2016-07-09");
                holder.server_num.setVisibility(View.INVISIBLE);
                holder.server_centel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        long serTransId = searchInfo.getSerTransId();

                    }
                });
            }else if ( "5".equals(transStatus)) {
                holder.transStatus.setText("状态:服务员已接");
                holder.server_centel.setText("撤单");
                holder.server_address.setText("已抢单");
                holder.server_finish_time.setText("2016-07-09");
                holder.server_num.setVisibility(View.INVISIBLE);
                holder.server_centel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        long serTransId = searchInfo.getSerTransId();

                    }
                });
            } else if ("6".equals(transStatus)) {
                holder.transStatus.setText("状态:任务正在执行");
                holder.server_centel.setVisibility(View.INVISIBLE);
                holder.server_address.setText("已完成");
                holder.server_num.setVisibility(View.INVISIBLE);
            } else if ("7".equals(transStatus)) {
                holder.transStatus.setText("状态:任务执行完成");
                holder.server_centel.setVisibility(View.INVISIBLE);
                holder.server_address.setText("已撤单");
                holder.server_num.setVisibility(View.INVISIBLE);
            }  else if ("8".equals(transStatus)) {
                holder.transStatus.setText("状态:任务执行完成");
                holder.server_centel.setVisibility(View.GONE);
                holder.server_address.setText("已取消");
                holder.server_num.setVisibility(View.GONE);
            } else  if ("9".equals(transStatus)||"11".equals(transStatus)){
                holder.transStatus.setText("状态:任务执行指派中");
                holder.server_centel.setVisibility(View.GONE);
                holder.server_address.setText("等待处理");
                holder.server_num.setVisibility(View.GONE);
            } else  if ("10".equals(transStatus)){
                holder.transStatus.setText("状态:任务执行指派中");
                holder.server_centel.setVisibility(View.GONE);
                holder.server_address.setText("等待处理");
                holder.server_num.setVisibility(View.GONE);
            }

            return itemView;
        }

        class ViewHolder {
            TextView uploadView, serverName, server_num, server_centel,
                    server_address, server_time_content, server_time,
                    server_rule_content, server_rule, server_surplus_num,
                    server_content_num, server_content, gift_packs,
                    transStatus, server_finish_time;
        }

    }


    @Override
    public void showProgress() {
        try {
            if (refrashData!=null){
                refrashData.setRefreshing(false);
            }
            showProgress(LlhMySubscribeFragment.this.getActivity());
        } catch (Exception E) {

        }
    }

    @Override
    public void hideProgress() {
        try {
            if (refrashData!=null){
                refrashData.setRefreshing(false);
            }
            closeProgress();
        } catch (Exception E) {

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }

    @Override
    public int getLayoutView() {
        return R.layout.llh_server_subscribe;
    }

    @Override
    public void initView(View view) {

    }

    @Override
    public void doBases() {

    }




}
